#include "mainscene.h"
#include<config.h>
#include <QIcon>
#include <QPainter>
#include<QMouseEvent>


mainscene::mainscene(QWidget *parent)
    : QWidget(parent)
{
        //初始化场景
        initScene();
}


mainscene::~mainscene()
{

}
void mainscene::initScene()
{
    //初始化窗口大小
    setFixedSize(GAME_WIDTH,GAME_HEIGHT);
    //设置窗口标题
    setWindowTitle(GAME_TITLE);
    //设置图标资源
    setWindowIcon(QIcon( GAME_ICON));
    //定时器设置
    m_Timer.setInterval(GAME_RATE);
    playGame();

}
void mainscene::playGame()
{
    //启动定时器
    m_Timer.start();
    //监听定时器
    connect(&m_Timer,&QTimer::timeout,[=](){
    //更新游戏中元素的坐标
    updatePosition();
    //重新绘制图片
    update();
    });
}

void mainscene::updatePosition()
{
    //更新地图坐标
    m_map.mapPosition();
    //测试子弹代码
        temp_bullet.m_Free = false;
        temp_bullet.updatePosition();
}

void mainscene::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    //绘制地图
    painter.drawPixmap(0,m_map.m_map1_posY , m_map.m_map1);
    painter.drawPixmap(0,m_map.m_map2_posY , m_map.m_map2);
    //绘制英雄
    painter.drawPixmap(m_hero.m_X,m_hero.m_Y,m_hero.m_Plane);
    //测试子弹代码
        painter.drawPixmap(temp_bullet.m_X,temp_bullet.m_Y,temp_bullet.m_Bullet);
}
void mainscene::mouseMoveEvent(QMouseEvent * event)
{
    int x =  event->x() -m_hero.m_Rect.width() * 0.5;
    int y =  event->y() -m_hero.m_Rect.height() *0.5;

    //边界检测

    if(x <= 0 )
    {
        x = 0;
    }
    if(x >= GAME_WIDTH - m_hero.m_Rect.width())
    {
        x = GAME_WIDTH - m_hero.m_Rect.width();
    }
    if(y <= 0)
    {
        y = 0;
    }
    if(y >= GAME_HEIGHT - m_hero.m_Rect.height())
    {
        y = GAME_HEIGHT - m_hero.m_Rect.height();
    }

    m_hero.setPosition(x,y);
}
